package nbcp.web.sys

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.web.bind.annotation.RestController


/**
 * Created by udi on 17-5-3.
 */
import org.slf4j.LoggerFactory
import org.springframework.data.mongodb.core.query.Criteria
import nbcp.base.comm.*
import nbcp.base.extend.*
import nbcp.comm.JsonpMapping
import nbcp.db.IdName
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.ExpressInfo
import nbcp.db.mongo.entity.OrderInfo
import nbcp.db.mq.mqr
import nbcp.service.srv
import nbcp.web.MyHttpRequestWrapper
import java.time.LocalDate
import java.time.LocalDateTime
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

@OpenAction
@Api(tags = arrayOf("OrderInfo"))
@RestController
@JsonpMapping("/info/order")
class Order_Controller {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @ApiOperation("查询订单")
    @JsonpMapping("/find")
    fun findOrder(
            orderCode: String,
            wxName: String,
            productName: String,
            mobile: String,
            expressNumber: String,
            status: OrderStatusEnum?,
            subOrderStart: Int,     //子订单数量 大于等于值
            subOrderEnd: Int,       //子订单数量 大于等于值
            groupStyle: Boolean,
            address: String,
            @JsonModel query: ListQueryModel,
            @ApiParam("查询的起始日期") startAt: LocalDate?,
            @ApiParam("查询的结束日期") endAt: LocalDate?,
            request: HttpServletRequest): ListResult<OrderInfo> {

        var where = mutableListOf<Criteria>();

        var corpId = request.Corp.id;

        if (corpId.HasValue) {
            where.add(mor.info.orderInfo.corp.id match corpId)
        }

        if (address.HasValue) {
            where.add(mor.info.orderInfo.receiveAddress.address match_like address)
        }


        if (status != null) {
            where.add(mor.info.orderInfo.status match status)
        }

        //如果传入的日期有值，添加条件，如果没有传入日期，那么久不需要添加条件
        if (startAt != null && endAt != null) {
            where.add(mor.info.orderInfo.createAt match_between (startAt to endAt.plusDays(1)));
        }

        if (orderCode.HasValue && orderCode != "") {
            where.add(mor.info.orderInfo.orderCode match_like orderCode!!)
        }

        if (orderCode != null && orderCode.HasValue) {
            where.add(mor.info.orderInfo.orderCode match_like orderCode);
        }

        if (wxName != null && wxName.HasValue) {
            where.add(mor.info.orderInfo.createBy.name match_like wxName);
        }

        if (productName != null && productName.HasValue) {
            where.add(mor.info.orderInfo.details.product.name match_like productName);
        }

        if (mobile != null && mobile.HasValue) {
            where.add(mor.info.orderInfo.payInfo.mobile match_like mobile);
        }


        if (expressNumber != null && expressNumber.HasValue) {
            where.add(mor.info.orderInfo.expressNumber match_like expressNumber);
        }
        var orderList = ListResult<OrderInfo>();

        if (groupStyle) {
//            return groupOrder(
//                    where,
//                    subOrderStart,
//                    subOrderEnd,
//                    query
//            );

            var headerCodes = mor.info.orderInfo.query()
                    .where(where)
                    .where(mor.info.orderInfo.groupOrderCount match_between (subOrderStart to subOrderEnd))
                    .where(mor.info.orderInfo.headerOrderCode match_dbColumn mor.info.orderInfo.orderCode)
                    .select(mor.info.orderInfo.orderCode)
                    .orderBy { it.id.desc }
                    .limit(query.skip, query.take)
                    .toListResult(String::class.java)

            orderList.total = headerCodes.total

            orderList.data = mor.info.orderInfo.query()
                    .where(mor.info.orderInfo.orderCode match_in headerCodes.data)
                    .orderBy { it.headerOrderCode.desc }
                    .orderBy { it.id.desc }
                    .toList();

            return orderList;
        }

        //根据订单状态(过滤条件)查询所有订单
        orderList = mor.info.orderInfo.query()
                .where(where)
                .orderBy { it.id.desc }
                .limit(query.skip, query.take)
                .toListResult()

        return orderList;
    }

//    /**
//     * 只返回分组的团长的订单.
//     */
//    fun groupOrder(
//            where: MutableList<Criteria>,
//            subOrderStart: Int,
//            subOrderEnd: Int,
//            @JsonModel query: ListQueryModel
//    ): ListResult<OrderQueryResult> {
//        var ret = ListResult<OrderQueryResult>();
//
//        var match = mutableListOf<String>()
//
//        if (subOrderStart >= 0 && subOrderEnd >= subOrderStart) {
//            match.add("subCount: { ##gte : ${subOrderStart + 1}  ,##lte: ${subOrderEnd + 1} }");
//        } else if (subOrderStart >= 0) {
//            match.add("subCount: { ##gte : ${subOrderStart + 1}  }");
//        } else if (subOrderEnd >= 0) {
//            match.add("subCount: { ##lte: ${subOrderEnd + 1} }");
//        }
//
//        match.addAll(where.map {
//            var ret = it.criteriaObject
//
//            var ret2 = BasicDBObject();
//            ret.keys.toTypedArray().forEach {
//                ret2.put("header." + it, ret[it]);
//            }
//            ret2.toJson().slice(1, -1);
//        })
//
//        //查询 团长订单
//        //添加两个字段, 是否团长,团员个数.
//        var queryJson = """
//{ ##addFields:{
//    header: { ##eq: ["##orderCode", "##headerOrderCode"] }
//} },
//{ ##group : {
//    _id: "##headerOrderCode",
//    subCount: { ##sum: 1 },
//    header: { ##addToSet: {
//          ##cond: { if: { ##eq: [ "##header", true ] }, then:
//            {${mor.info.orderInfo.getColumns().map { """ ${it}:"##${it}" """ }.joinToString(",")} },
//          else: null }
//    } }
//} },
//{ ##project: {
//    subCount: "##subCount",
//    header: { ##arrayElemAt: [ { ##filter : {
//                    input : "##header",
//                    as: "item",
//                    cond: { ##and: [
//                        { ##ne: [ "####item" , null ]}
//                    ]}
//            } } , 0 ] }
//} },
//{ ##match: {
//${match.joinToString(",")}
//} },
//{ ##project: {"_id":"##_id" ,subCount: "##subCount" } }
//""".replace("##", "$")
//
//        var queryData = queryJson + """,
//{ ##sort : { "_id" : -1 } } ,
//{ ##skip : ${query.skip} },
//{ ##limit : ${query.take} }""".replace("##", "$");
//
//        val result = mor.mongoTemplate.aggregatePipelineEx(mor.info.orderInfo, queryData)
//        var headerOrderCodes = result.map { it.getValue("_id") };
//
//        if (headerOrderCodes.size > 0) {
//            ret.data = mor.info.orderInfo.query()
//                    .where(mor.info.orderInfo.headerOrderCode match_in headerOrderCodes.toTypedArray())
//                    .toList(OrderQueryResult::class.java);
//
//            ret.data.sortBy { it.headerOrderCode + "." + it.id }
//
////                    .sortedWith(Comparator<OrderQueryResult> { a,b ->
////                        var ret = a.headerOrderCode.compareTo(b.headerOrderCode);
////
////                        if (ret != 0) return@Comparator ret;
////                        return@Comparator a.id.compareTo(b.id);
////                    }).toMutableList();
//
//
//            //重新赋 subCount 值.
//            ret.data.forEach {
//                it.subCount = (result.firstOrNull { groupItem -> groupItem.getValue("_id").toString() == it.orderCode }?.getValue("subCount")?.AsInt(1)
//                        ?: 1) - 1;
//            }
//        }
//
//        if (query.skip == 0) {
//            if (headerOrderCodes.size < query.take) {
//                ret.total = headerOrderCodes.size;
//            } else {
//
//                var queryTotal = queryJson + """ ,
//{ ##group: { _id: 1 , sum:{ ##sum: 1 } }  } """.replace("##", "$");
//                ret.total = mor.mongoTemplate.aggregatePipelineEx(mor.info.orderInfo, queryTotal).first().get("sum").AsInt();
//            }
//        }
//
//        return ret;
//    }


    @ApiOperation("更改物流信息,并把状态改为发货")
    @JsonpMapping("/setStatus")
    fun SendOrder(
            orderCode: String,
            status: OrderStatusEnum,
            express: IdName?,
            expressNumber: String,
            request: HttpServletRequest
    ): JsonResult {

        //将订单的物流信息更新上去
        mor.info.orderInfo.update()
                .where { it.orderCode match orderCode }
                .where { it.corp.id match request.Corp.id }
                .setIf(status == OrderStatusEnum.Delivered, { it.express to express })
                .setIf(status == OrderStatusEnum.Delivered, { it.expressNumber to expressNumber })
                .set(mor.info.orderInfo.status, status)
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult(msg = "更改订单状态失败")
        }

//        mqr.wx.expressMessage.send(orderCode);
        return JsonResult()
    }


//    data class OrderDetailResult(
//            var orderInfo: OrderInfo = OrderInfo(),
//            var activityStatus: GroupStatusEnum = GroupStatusEnum.Empty
//    ) {}

    @ApiOperation("根据订单号查询订单信息")
    @JsonpMapping("/findByOrderCode")
    fun findByOrderCode(
            orderCode: String
    ): ApiResult<OrderInfo> {
        val orderInfo = mor.info.orderInfo.query()
                .where(mor.info.orderInfo.orderCode match orderCode)
                .toEntity()

        if (orderInfo == null) {
            return ApiResult("查询订单错误")
        }

        //根据订单号查询订单的详细信息
        return ApiResult.of(data = orderInfo)

    }

    @JsonpMapping("/getExpressList")
    fun getExpressList(
            session: HttpServletRequest
    ): ApiResult<List<ExpressInfo>> {

        val res = mor.info.expressInfo.query().toList()
        return ApiResult.of(data = res)
    }


    @ApiOperation("小程序端发货")
    @JsonpMapping("/deliver")
    fun deliverOrder(
            orderId: String, expressName: String, expressNumber: String
    ): JsonResult {
        var orderInfo = mor.info.orderInfo.queryById(orderId).toEntity();

        if (orderInfo == null) {
            return JsonResult("找不到订单")
        }
        if (orderInfo.status != OrderStatusEnum.Prepare) {
            return JsonResult("订单状态必须是准备状态才能发货")
        }

        mor.info.orderInfo.updateById(orderInfo.id)
                .set(mor.info.orderInfo.status, OrderStatusEnum.Delivered)
                .set(mor.info.orderInfo.sentAt, LocalDateTime.now())
                .exec();

        //发送短信  发送
//        srv.sms.sendDeliveredCode(orderInfo.payInfo.mobile, orderInfo.createBy.name, orderInfo.orderCode, expressName, expressNumber);
//        mqr.wx.expressMessage.send(orderInfo.orderCode);

        return JsonResult()

    }


}